package net.didactylos.helpline.action;

import java.util.Date;
import java.util.List;

import org.hibernate.Session;

import net.didactylos.helpline.data.*;
import net.didactylos.helpline.servlet.EmailManager;
import net.didactylos.helpline.stripes.bean.HelplineActionBean;
import net.didactylos.helpline.stripes.security.Capabilities;
import net.didactylos.helpline.stripes.security.Secured;
import net.sourceforge.stripes.action.*;
import net.didactylos.helpline.data.Message;
import net.sourceforge.stripes.controller.LifecycleStage;

public class ReplyAction extends HelplineActionBean
{
	private long messageId;
	
	private Message message;
	
	private Message draft;
	
	private boolean editContact;

	public long getMessageId()
	{
		return messageId;
	}

	public void setMessageId(long messageId)
	{
		this.messageId = messageId;
	}

	public Message getMessage()
	{
		return message;
	}

	public void setMessage(Message message)
	{
		this.message = message;
	}

	public Message getDraft()
	{
		return draft;
	}

	public void setDraft(Message draft)
	{
		this.draft = draft;
	}
	
	public boolean isEditContact()
	{
		return editContact;
	}

	public void setEditContact(boolean editContact)
	{
		this.editContact = editContact;
	}

//	@Before(stages=LifecycleStage.BindingAndValidation)
//	public Resolution preLoad()
//	{
//		Session session = getContext().getSession();
//		if (messageId > 0)
//		{
//			message = (Message) session.get(Message.class, messageId);
//			return null;
//		}
//		
//		message = getContext().getMessage();
//		
//		return null;
//	}
	
	@DontValidate
	@Secured(Capabilities.SIGN_IN)
	public Resolution editContact()
	{
		editContact = true;
		return new ForwardResolution("reply.jspx");
	}

	@SuppressWarnings("unchecked")
	@DontValidate
	@DefaultHandler
	@Secured(Capabilities.SIGN_IN)
	public Resolution view()
	{
		if (message == null)
		{
			Session session = getContext().getSession();
			List<Message> messages = session
			.createQuery("from Message as msg where msg.status=1")
			.list();
			
			if (messages.size() == 0)
			{
				getContext().getMessages().add(new LocalizableMessage("replyNothingMessage"));
				return new RedirectResolution("/");
			}
			message = messages.get(0);
			//message.setStatus(0);
			
			session.update(message);
			
			// set owner...
			getContext().setMessage(message);
			
			// User owns entire conversation for the duration of the edit.
			Conversation conversation = message.getConversation();
			conversation.setOwner(getContext().getUser());
			session.update(conversation);
			
			
			String subject = message.getSubject().toUpperCase();
			if (subject.startsWith("FWD:")
					|| subject.startsWith("FW:"))
			{
				// Good chance the email was forwarded.
				getContext().getMessages().add(new LocalizableMessage("possibleForwardMessage"));
			}
		}
		return new ForwardResolution("reply.jspx");
	}
	
	@Secured(Capabilities.SIGN_IN)
	public Resolution edit()
	{
		draft.setAuthor(getContext().getUser());
		draft.setSubject(message.getSubject());
		draft.setConversation(message.getConversation());
		draft.setCreateTime(new Date());
		draft.setStatus(MessageStatus.DRAFT);
		draft.setInReplyTo(message);
		draft.setType(MessageType.OUTBOUND);
		
		Session session = getContext().getSession();
		session.saveOrUpdate(draft);
        //session.getTransaction().commit();
        	
        getContext().getMessages().add(
				new LocalizableMessage("draftSavedMessage", message
						.getAuthor().getDisplayName()));
		
        return new RedirectResolution("/Conversation.action?message=" + message.toString());
	}
	
	/**
	 * This action restarts the edit process by .
	 * @return
	 */
	@Secured(Capabilities.SIGN_IN)
	public Resolution reedit()
	{
		Session session = getContext().getSession();
		message.setStatus(MessageStatus.DRAFT);
		
		Message parent = message.getInReplyTo();

		Queue emailQueue = (Queue) session
		.createQuery("from Queue as queue where queue.name = ?")
		.setParameter(0, "Email")
		.uniqueResult();
		
		message.setQueue(null);
		parent.setQueue(emailQueue);
		
		session.saveOrUpdate(message);
		
        return new RedirectResolution("/Conversation.action?message=" + parent.toString());
	}

	@Secured(Capabilities.SIGN_IN)
	public Resolution commit()
	{
		draft.setAuthor(getContext().getUser());
		draft.setSubject(message.getSubject());
		draft.setConversation(message.getConversation());
		draft.setCreateTime(new Date());
		draft.setStatus(MessageStatus.NEED_APPROVE);
		draft.setInReplyTo(message);
		draft.setType(MessageType.OUTBOUND);
		
		Conversation conv = message.getConversation();
		conv.setOwner(null);
		
		Session session = getContext().getSession();
		
		Queue checkQueue = (Queue) session
		.createQuery("from Queue as queue where queue.name = ?")
		.setParameter(0, "Check")
		.uniqueResult();
		
		message.setQueue(null);
		draft.setQueue(checkQueue);
		
		session.saveOrUpdate(draft);
		session.update(conv);
		session.update(message);
		
        //session.getTransaction().commit();
        
        getContext().getMessages().add(
				new LocalizableMessage("replySuccessMessage", message
						.getAuthor().getDisplayName()));
		
        return new RedirectResolution("/");
	}
	
	@Secured(Capabilities.SIGN_IN)
	public Resolution send()
	{
		message.setTemplate((Template) getContext().getSession().createCriteria(Template.class).uniqueResult());
		
		EmailManager.sendEmail(message);
		
		message.setQueue(null);
		message.setStatus(MessageStatus.SENT);
		
		Message parent = message.getInReplyTo();
		parent.setStatus(MessageStatus.REPLIED);
		
		Conversation conv = message.getConversation();
		conv.setOwner(null);
		
		Session session = getContext().getSession();
		session.update(message);
		session.update(parent);
		session.update(conv);
		
		getContext().getMessages().add(new LocalizableMessage("approveSuccessMessage", parent
				.getAuthor().getDisplayName()));
		
        return new RedirectResolution("/");
	}
}
